import re
import datetime
import random
from captcha.models import CaptchaStore
from rest_framework import serializers
from django.db.models import F
from .models import Province, City, District, ShortMsg, BankCode
from core.tools.short_message import ShortMessage
from finance_c2c.settings import REGEX_MOBILE
from finance_c2c.settings import YuiPinAppId, YuiPinAppKey


class ProvinceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Province
        fields = ("name",)


class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = ("name",)


class DistrictSerializer(serializers.ModelSerializer):
    class Meta:
        model = District
        fields = ("name",)


class ShortMsgSerializer(serializers.ModelSerializer):
    tel = serializers.CharField(write_only=True, label="手机号", max_length=11, min_length=11, help_text="手机号",
                                error_messages={
                                    "blank": "手机号不能为空",
                                    "max_length": "请正确填写手机号",
                                    "min_length": "请正确填写手机号"
                                })
    # captcha = serializers.CharField(write_only=True, label="图形验证码", max_length=4, min_length=4, help_text="图形验证码",
    #                                 error_messages={
    #                                     "max_length": "图片验证码格式错误",
    #                                     "min_length": "图片验证码格式错误",
    #                                     "required": "请输入图片验证码"
    #                                 })
    captcha = serializers.CharField(write_only=True, label="图形验证码", help_text="图形验证码", required=False, allow_blank=True)
    # ima_id = serializers.CharField(required=True, write_only=True, allow_blank=False, help_text="图片验证码id")
    ima_id = serializers.CharField(required=False, write_only=True, allow_blank=True, help_text="图片验证码id")

    class Meta:
        model = ShortMsg
        # fields = ("tel", )
        fields = ("tel", "captcha", "ima_id")

    def validate_captcha(self, captcha):
        try:
            captcha = captcha.lower()
        except:
            raise serializers.ValidationError("图片验证码错误")
        image_code = CaptchaStore.objects.filter(
            id=self.initial_data['ima_id']).first()
        if image_code and datetime.datetime.now() > image_code.expiration:
            raise serializers.ValidationError('图片验证码过期')
        else:
            if image_code and image_code.response == captcha:
                pass
            else:
                raise serializers.ValidationError("图片验证码错误")

    def validate_tel(self, tel):
        if not re.match(REGEX_MOBILE, tel):
            raise serializers.ValidationError("手机号不合法")
        return tel

    def create(self, validated_data):
        code = random.randint(1000, 9999)
        tel = validated_data["tel"]
        now_time = datetime.datetime.now()
        s_info = ShortMsg.objects.filter(tel=tel)
        if s_info.exists():
            instance = s_info.first()
            # 如果有更新时间
            if instance.update_time:
                # 如果更新时间不是今天
                if instance.update_time.strftime("%Y-%m-%d") != now_time.strftime("%Y-%m-%d"):
                    resp = ShortMessage.send_single(tel, code, 325192, YuiPinAppId, YuiPinAppKey)
                    if resp.get("result") == 0 and resp.get("errmsg") == 'OK':
                        instance.update_time = now_time
                        instance.create_time = now_time
                        instance.code = code
                        instance.num = 1
                        instance.status = True
                        instance.save()
                        return instance
                    else:
                        raise serializers.ValidationError(resp.get("errmsg"))
                # 如果更新时间是今天 但是发送短信的数量小于等于3
                elif instance.update_time.strftime("%Y-%m-%d") == now_time.strftime("%Y-%m-%d") and instance.num < 3:
                    if instance.get_update_time():
                        resp = ShortMessage.send_single(tel, code, 325192, YuiPinAppId, YuiPinAppKey)
                        if resp.get("result") == 0 and resp.get("errmsg") == 'OK':
                            instance.update_time = now_time
                            instance.create_time = now_time
                            instance.code = code
                            instance.num = F("num") + 1
                            instance.status = True
                            instance.save()
                            return instance
                        else:
                            raise serializers.ValidationError(resp.get("errmsg"))
                    # 如果时间过短
                    else:
                        raise serializers.ValidationError("请稍后重试,操作太频繁 ")
                else:
                    raise serializers.ValidationError("今天短信发送数量过多")
            else:
                resp = ShortMessage.send_single(tel, code, 325192, YuiPinAppId, YuiPinAppKey)
                if resp.get("result") == 0 and resp.get("errmsg") == 'OK':
                    instance.update_time = now_time
                    instance.create_time = now_time
                    instance.code = code
                    instance.num = F("num") + 1
                    instance.status = True
                    instance.save()
                    return instance
                else:
                    raise serializers.ValidationError(resp.get("errmsg"))
        else:
            resp = ShortMessage.send_single(tel, code, 325192, YuiPinAppId, YuiPinAppKey)
            if resp.get("result") == 0 and resp.get("errmsg") == 'OK':
                return ShortMsg.objects.create(
                    tel=tel,
                    update_time=now_time,
                    create_time=now_time,
                    code=code,
                    num=1,
                    status=True
                )
            else:
                raise serializers.ValidationError(resp.get("errmsg"))


class BankCodeSerializer(serializers.ModelSerializer):
    label = serializers.SerializerMethodField()
    value = serializers.SerializerMethodField()

    def get_label(self, obj):
        return obj.name

    def get_value(self, obj):
        return obj.id

    class Meta:
        model = BankCode
        fields = ("label", "value")
